package com.blockmeta.bbs.businesslibrary.widget;

import android.net.Uri;
import android.text.TextUtils;

import com.blockmeta.bbs.businesslibrary.util.DeepLinkUtils;
import com.tencent.smtt.export.external.interfaces.SslError;
import com.tencent.smtt.export.external.interfaces.SslErrorHandler;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;

public abstract class NestWebViewClient extends WebViewClient
{
	public static Map<String, String> parseUrlParams(String encodeData)
	{
		Map<String, String> map = new HashMap<String, String>();

		StringTokenizer tokenizer = new StringTokenizer(encodeData, "&");
		while (tokenizer.hasMoreTokens())
		{
			String token = tokenizer.nextToken();
			String value = null;

			int index = token.indexOf('=');
			if (index > 0)
			{
				value = token.substring(index + 1);
				token = token.substring(0, index);

				map.put(URLDecoder.decode(token), URLDecoder.decode(value));
			}
		}

		return map;
	}

	protected boolean isDeepLink(String url)
	{
		if(url == null){
			return false;
		}
		//以下这些链接需要跳转到native，除了链作自身
		Uri uri = Uri.parse(url);
		if(url.contains("8btc.com/farms")){
			return false;
		}
		if (("blockmeta".equals(uri.getScheme()) || ("8btc.com".equals(uri.getHost())
				|| "m.8btc.com".equals(uri.getHost())) || uri.getHost().contains("chainnode.com") || "www.8btc.com".equals(uri.getHost()))
				&& !url.contains("/mall/")){
			return true;
		}
		else
		{
			return url.contains("blockmeta");
		}
	}

	protected void doDeepLink(WebView view, String linkUrl)
	{
		if (!TextUtils.isEmpty(linkUrl)) {
			String url = DeepLinkUtils.regexUri(linkUrl);
			DeepLinkUtils.jumpToTarget(view.getContext(), Uri.parse(url));
		}
	}


	@Override
	public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error)
	{
		if (handler != null)
		{
			handler.proceed();
		}
	}
}
